package com.avoscloud.chat.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.example.studycard.R;
import com.avoscloud.chat.avobject.AddRequest;
import com.avoscloud.chat.avobject.User;
import com.avoscloud.chat.db.DBHelper;
import com.avoscloud.chat.service.UpdateService;
import com.avoscloud.chat.service.UserService;
import com.avoscloud.chat.service.chat.IM;
import com.avoscloud.chat.ui.view.BaseListView;
import com.avoscloud.chat.util.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lzw on 14-9-17.
 */
public class PersonalInfoSettingActivity extends BaseActivity implements
		View.OnClickListener {
	private static final int IMAGE_PICK_REQUEST = 1;
	private static final int CROP_REQUEST = 2;
	TextView usernameView, genderView;
	ImageView avatarView;
	View usernameLayout, avatarLayout, genderLayout;
	IM im;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_info_setting);
		findView();// 导入布局
		refresh();// 更新用户信息
	}

	//修改信息返回时保存并刷新界面
	SaveCallback saveCallback = new SaveCallback() {
		@Override
		public void done(AVException e) {
			refresh();
		}
	};

	private void refresh() {
		AVUser curUser = AVUser.getCurrentUser();
		usernameView.setText(curUser.getUsername());// 显示用户名
		genderView.setText(User.getGenderDesc(curUser));// 显示所选的性别
		UserService.displayAvatar(User.getAvatarUrl(curUser), avatarView);// 设置用户头像
	}

	private void findView() {
		initActionBar(R.string.user_info_setting);
		usernameView = (TextView) findViewById(R.id.username);
		avatarView = (ImageView) findViewById(R.id.avatar);
		avatarLayout = findViewById(R.id.avatarLayout);
		genderLayout = findViewById(R.id.sexLayout);
		genderView = (TextView) findViewById(R.id.sex);

		avatarLayout.setOnClickListener(this);
		genderLayout.setOnClickListener(this);
	}

	// 监听不同按钮执行不同操作
	@Override
	public void onClick(View v) {
		int id = v.getId();
		// 若是更换头像则调用系统相册并返回一个标志IMAGE_PICK_REQUEST，请求码
		if (id == R.id.avatarLayout) {
			Intent intent = new Intent(Intent.ACTION_PICK, null);
			intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
					"image/*");
			startActivityForResult(intent, IMAGE_PICK_REQUEST);

		} else if (id == R.id.sexLayout) {
			showSexChooseDialog();// 选择性别页面的相关设置
		}
	}

	/*
	 * 选择性别的dialog 以0和1来标志女和男 选择结束之后将性别保存到用户表并回调saveCallback，重新获取数据
	 */
	private void showSexChooseDialog() {
		AVUser user = AVUser.getCurrentUser();
		int checkItem = User.getGender(user) == User.Gender.Male ? 0 : 1;
		new AlertDialog.Builder(ctx)
				.setTitle(R.string.sex)
				.setSingleChoiceItems(User.genderStrings, checkItem,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								User.Gender gender;
								if (which == 0) {
									gender = User.Gender.Male;
								} else {
									gender = User.Gender.Female;
								}
								UserService.saveSex(gender, saveCallback);
								dialog.dismiss();
							}
						}).setNegativeButton(R.string.cancel, null).show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Logger.d("on Activity result " + requestCode + " " + resultCode);
		super.onActivityResult(requestCode, resultCode, data);// data是uri格式的操作数据
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == IMAGE_PICK_REQUEST) {
				Uri uri = data.getData();// 若请求码为获取图片则获取图片地址
				startImageCrop(uri, 200, 200, CROP_REQUEST);// 设置头像的长宽（截取图像）
			} else if (requestCode == CROP_REQUEST) {
				final String path = saveCropAvatar(data);
				new SimpleNetTask(ctx) {
					@Override
					protected void doInBack() throws Exception {
						UserService.saveAvatar(path);
					}

					@Override
					protected void onSucceed() {
						refresh();
					}
				}.execute();

			}
		}
	}

	public Uri startImageCrop(Uri uri, int outputX, int outputY, int requestCode) {
		Intent intent = null;
		intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		String outputPath = PathUtils.getAvatarTmpPath();
		Uri outputUri = Uri.fromFile(new File(outputPath));
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
		intent.putExtra("return-data", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", false); // face detection
		startActivityForResult(intent, requestCode);
		return outputUri;
	}

	// 保存图片并转为圆角图片
	private String saveCropAvatar(Intent data) {
		Bundle extras = data.getExtras();
		String path = null;
		if (extras != null) {
			Bitmap bitmap = extras.getParcelable("data");
			if (bitmap != null) {
				bitmap = PhotoUtils.toRoundCorner(bitmap, 10);
				String filename = new SimpleDateFormat("yyMMddHHmmss")
						.format(new Date());
				path = PathUtils.getAvatarDir() + filename;
				Logger.d("save bitmap to " + path);
				PhotoUtils.saveBitmap(PathUtils.getAvatarDir(), filename,
						bitmap, true);
				if (bitmap != null && bitmap.isRecycled() == false) {
					// bitmap.recycle();
				}
			}
		}
		return path;
	}
}
